//
//  LCHtmlController.m
//  wan77
//
//  Created by jiukuyinyue on 2017/8/25.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCCreateWenHtmlVC.h"
#import "LCViewController+YQShare.h"

#define scriptNameArr @[]

@interface LCCreateWenHtmlVC ()

@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) CGFloat delayTime;

@end

@implementation LCCreateWenHtmlVC

- (void)loadView {
    [super loadView];
    self.title = self.vcInitDictData[@"title"];
    _link = self.vcInitDictData[@"link"];
    self.rightTitle = self.vcInitDictData[@"rightTitle"];
}

- (void)back
{
    if (_refreshBlock != nil) {
        _refreshBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)rightBtnAction{
    NSString *clzName = @"LCCreateWenHtmlVC";
    Class clz = NSClassFromString(clzName);
    LCViewController *viewController = [[clz alloc] init];
    viewController.vcInitDictData = [NSDictionary dictionaryWithObjectsAndKeys:@"我的文章", @"title",
                                     [NSString stringWithFormat:@"http://fuyin-admin.app.inping.com/home/edit/at_list?usercode=%@",[_UserM usercode]], @"link", nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:scriptNameArr[i]];
    }
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:scriptNameArr[i]];
    }
}
- (void)dealloc {
    NSLog(@"__func__dealloc = %s", __func__);
    @try {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    } @catch (NSException *exception) {}
    _webView.UIDelegate = nil;
    _webView.navigationDelegate = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"调转链接 %@",_link);

    [self setupWebView];
    [self setupProgressView];
}

#pragma mark -
-(void)setupWebView{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tabBarController.tabBar.translucent = NO;
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@""];
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:userScript];

    _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
    
    [self.view addSubview:_webView];
    _webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_link]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
    [_webView loadRequest:request];//加载
    [self setupWebViewLayout];
}

- (void)setupWebViewLayout
{
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-0);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-0);
        }
    }];
}
- (void)setupProgressView
{
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 2)];
    [self.view addSubview:_progressView];
    _progressView.progressTintColor = [UIColor redColor];//RGBColor(58, 150, 246)
    _progressView.trackTintColor = [UIColor clearColor];
    [self.view bringSubviewToFront:self.progressView];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });

    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    }
}


- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"message.name = %@ message.body = %@", message.name,message.body);
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
}

/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
     // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}


//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = self.webView.title;
}

// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

///禁止键盘弹出时WKWebView自动滑动
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}

@end
